package com.example.personalizededucationsystem.service;

import com.example.personalizededucationsystem.model.KnowledgePoint;
import com.example.personalizededucationsystem.repository.KnowledgePointRepository;
import com.example.personalizededucationsystem.utils.ApprovalStatus;
import com.example.personalizededucationsystem.utils.PagedResult;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class KnowledgeService {
    private final KnowledgePointRepository knowledgePointRepository;

    public KnowledgeService(KnowledgePointRepository knowledgePointRepository) {
        this.knowledgePointRepository = knowledgePointRepository;
    }

    public PagedResult<KnowledgePoint> getKnowledgePointsByStatusAndSubjects(ApprovalStatus status, int page, String keyword, String subject) {
        Pageable pageable = PageRequest.of(page - 1, 10, Sort.by(Sort.Direction.DESC, "kpId"));
        Page<KnowledgePoint> kpPage;
        if (keyword != null && !keyword.trim().isEmpty()) {
            kpPage = knowledgePointRepository.searchByStatusAndSubjectAndKeyword(status, subject, keyword, pageable);
        } else {
            kpPage = knowledgePointRepository.findByStatusAndSubject(status, subject, pageable);
        }
        return new PagedResult<>(kpPage.getContent(), kpPage.getTotalElements());
    }

    public PagedResult<KnowledgePoint> getKnowledgePointsByStatus(ApprovalStatus status, int page, String keyword) {
        Pageable pageable = PageRequest.of(page - 1, 10, Sort.by(Sort.Direction.DESC, "kpId"));
        Page<KnowledgePoint> kpPage;

        if (keyword != null && !keyword.trim().isEmpty()) {
            kpPage = knowledgePointRepository.findByStatusAndNameContainingIgnoreCase(status, keyword, pageable);
        } else {
            kpPage = knowledgePointRepository.findByStatus(status, pageable);
        }

        return new PagedResult<>(kpPage.getContent(), kpPage.getTotalElements());
    }


    public boolean approveKnowledgePoint(Long id) {
        KnowledgePoint kp = knowledgePointRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("知识点未找到"));
        kp.setStatus(ApprovalStatus.APPROVED);
        knowledgePointRepository.save(kp);
        return true;
    }

    public boolean rejectKnowledgePoint(Long id) {
        KnowledgePoint kp = knowledgePointRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("知识点未找到"));
        kp.setStatus(ApprovalStatus.REJECTED);
        knowledgePointRepository.save(kp);
        return true;
    }
}
